package com.br.aiops.cycle;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.apache.commons.lang3.time.FastDateFormat;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;
import java.util.Objects;

@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class Cycle {

    private static final Logger LOGGER = LoggerFactory.getLogger(Cycle.class);

    /**
     * 闭区间
     */
    private long start;

    /**
     * 开区间
     */
    private long end;

    /**
     * duration
     */
    private int duration;

    public Cycle(int duration) {
        long current = Long.parseLong(FastDateFormat.getInstance("yyyyMMddHHmm").format(new Date()));
        this.start = current / duration * duration;
        this.end = next(this.start, duration);
        this.duration = duration;
    }

    public final Long next(Long start, int minutes) {
        Date date = null;
        try {
            date = FastDateFormat.getInstance("yyyyMMddHHmm").parse(start.toString());
        } catch (ParseException e) {
            LOGGER.error("解析错误。", e);
        }
        Objects.requireNonNull(date);
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        calendar.add(Calendar.MINUTE, minutes);
        return Long.valueOf(FastDateFormat.getInstance("yyyyMMddHHmm").format(calendar.getTime()));
    }

    public String cycleKey() {
        return start + "_" + end;
    }
}
